#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 81
#define BUF_SIZE 4069

char * s_gets(char *, int);
void append(FILE *, FILE *);

int main(void)
{
    unsigned files;

    FILE * dst;
    FILE * src;

    char srcname[LEN];
    char dstname[LEN];
    char ch;

    puts("Please enter the name of destination name.");
    while (s_gets(dstname, LEN) == NULL || dstname[0] == '\0') {
        puts("enter destination name failed!");
        puts("Plase enter the name of destination name.");
    }

    if ((dst = fopen(dstname, "a+")) == NULL) {
        fprintf(stderr, "Create destination file %s failed!\n", dstname);
        exit(EXIT_FAILURE);
    }

    if (setvbuf(dst, NULL, _IOFBF, BUF_SIZE) != 0) {
        fprintf(stderr, "Cant't create output buffer.\n");
        exit(EXIT_FAILURE);
    }

    printf("Enter the name of first source file (empty line to quit): ");
    while (s_gets(srcname, LEN) && srcname[0] != '\0') {
        if (strcmp(srcname, dstname) == 0) {
            printf("Can't append file to itself\n");

        } else if ((src = fopen(srcname, "r")) == NULL) {
            fprintf(stderr, "Open file %s failed.", srcname);

        } else {
            if (setvbuf(src, NULL, _IOFBF, BUF_SIZE) != 0) {
                fputs("Can't create input file buffer\n", stderr);
                continue;
            }

            append(dst, src);

            if (ferror(src)) {
                fprintf(stderr, "Error in reading file %s\n", srcname);
                exit(EXIT_FAILURE);
            }

            if (ferror(dst)) {
                fprintf(stderr, "Error in writing file %s.\n", dstname);
                exit(EXIT_FAILURE);
            }

            if (EOF == fclose(src)) {
                fprintf(stderr, "file %s close failed.\n", srcname);
                exit(EXIT_FAILURE);
            }

            ++files;
            printf("File %s appended.\n", srcname);
            printf("Next file (empty line to quit):");
        }
    }

    printf("Done appending. %d files appended.\n", files);
    rewind(dst);
    printf("%s contents:\n", dstname);
    while ((ch = getc(dst)) != EOF)
        putc(ch, stdout);

    puts("done displaying.");
    fclose(dst);

    return 0;

}


void append(FILE * dst, FILE *src)
{
    size_t bytes;
    static char temp[BUF_SIZE];

    while ((bytes = fread(temp, sizeof(char), BUF_SIZE, src)) > 0)
        fwrite(temp, sizeof(char), BUF_SIZE, dst);
}

char * s_gets(char * pt, int len)
{
    char * ret_val;
    char * find;

    ret_val = fgets(pt, len, stdin);
    if (ret_val) {
        find = strchr(pt, '\n');
        if (find)
            *find = 0;
        else
            while (getchar() != '\n')
                ;
    }
    return ret_val;
}
